<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.sx.pojo.Goods" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>
<!-- 引入 Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
<!-- 引入 SweetAlert2 的 CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.3/dist/sweetalert2.min.css">
<style>
    /* 整体页面背景设置为淡灰色，营造简洁清爽感 */
    body {
        font-family: 'Roboto', Arial, sans-serif;
        background-color: #f4f4f9;
        margin: 0;
        padding: 0;
        color: #333;
    }

    /* 页面主容器，设置宽度、居中、内边距、背景色及轻微阴影效果 */
    .main-container {
        width: 90%;
        margin: 50px auto;
        padding: 40px;
        background-color: #fff;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
        border-radius: 10px;
    }

    /* 标题样式，字体大小、加粗、颜色及下边距 */
    h1 {
        font-size: 36px;
        font-weight: bold;
        color: #007bff;
        margin-bottom: 30px;
    }

    /* 筛选表单样式，调整整体布局更紧凑合理 */
    .filter-form {
        background-color: #f9f9f9;
        padding: 20px;
        border-radius: 10px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
        margin-bottom: 20px;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        align-items: center;
    }

    .filter-form label {
        font-weight: bold;
        margin-bottom: 5px;
        min-width: 100px;
    }

    .filter-form input,.filter-form select {
        margin-bottom: 15px;
        width: 100%;
        max-width: 200px;
        padding: 8px;
        border: 1px solid #ccc;
        border-radius: 4px;
    }

    .filter-form select {
        appearance: none;
        background-color: #fff;
        background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2F%3E%3Cpath%20d%3D%22M7%2010l5%205%205-5z%22%2F%3E');
        background-repeat: no-repeat;
        background-position: right 0.75rem center;
        background-size: 16px 12px;
    }

    .filter-form select:focus {
        border-color: #80bdff;
        outline: 0;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }

    .filter-form button {
        margin-bottom: 0;
        width: auto;
        padding: 10px 20px;
        border: none;
        border-radius: 4px;
        background-color: #007bff;
        color: #fff;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }

    .filter-form button:hover {
        background-color: #0056b3;
    }

    /* 表格容器，设置相对定位方便内部元素定位 */
    .table-container {
        position: relative;
        overflow-x: auto;
    }

    /* 表格样式，紧凑布局、边框、背景色及文本颜色 */
    table {
        width: 100%;
        border-collapse: collapse;
        border: 1px solid #e0e0e0;
        background-color: #f9f9f9;
        color: #333;
    }

    /* 表头样式，背景色、文字颜色、内边距、边框及轻微阴影 */
    thead th {
        background-color: #007bff;
        color: white;
        padding: 18px;
        border: 1px solid #e0e0e0;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        text-align: center;
    }

    /* 表格数据单元格样式，内边距、边框及鼠标悬停时的背景色变化 */
    tbody td {
        padding: 18px;
        border: 1px solid #e0e0e0;
        transition: background-color 0.3s ease;
        font-size: 18px;
        text-align: center;
    }

    tbody td:hover {
        background-color: #e6e6e6;
    }

    /* 偶数行变色效果 */
    tbody tr:nth-child(even) {
        background-color: #f5f5f9;
    }

    /* 利润列样式，设置文本颜色为绿色（可根据喜好调整） */
    .profit-column {
        color: #28a745;
    }
</style>
<script>
    function validateForm() {
        // 简单验证，可根据实际需求扩展更严谨的验证逻辑
        return true;
    }

    function showDetails(goodId) {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', '/getGoodDetail?id=' + goodId, true);
        xhr.onload = function () {
            if (xhr.status >= 200 && xhr.status < 300) {
                if (xhr.responseText) {
                    try {
                        let data = JSON.parse(xhr.responseText);
                        showGoodsData(data);
                    } catch (e) {
                        console.error('JSON 解析错误:', e);
                        Swal.fire({
                            title: '错误',
                            text: '解析 JSON 数据时出错，请稍后重试',
                            icon: 'error'
                        });
                    }
                } else {
                    console.error('未收到响应数据');
                    Swal.fire({
                        title: '错误',
                        text: '未收到响应数据，请稍后重试',
                        icon: 'error'
                    });
                }
            } else {
                console.error('请求错误:', xhr.statusText);
                Swal.fire({
                    title: '错误',
                    text: '请求失败，请稍后重试',
                    icon: 'error'
                });
            }
        };
        xhr.onerror = function () {
            console.error('网络错误');
            Swal.fire({
                title: '错误',
                text: '网络错误，请稍后重试',
                icon: 'error'
            });
        };
        xhr.send();
    }


    function showGoodsData(data) {
        // 检查数据是否存在并提供默认值
        const safeData = {
            id: data && data.id? data.id : 'N/A',
            categoryId: data && data.categoryId? data.categoryId : 'N/A',
            name: data && data.name? data.name : 'N/A',
            price: data && data.price? data.price : 0,
            description: data && data.description? data.description : 'N/A',
            inPrice: data && data.inPrice? data.inPrice : 0,
            number: data && data.number? data.number : 0,
            createDate: data && data.createDate? data.createDate : 'N/A',
            shelfLife: data && data.shelfLife? data.shelfLife : 0,
            supplier_id: data && data.supplier_id? data.supplier_id : 'N/A'
        };

        // 直接在 showGoodsData 中处理日期转换
        let createDate = 'N/A';
        if (safeData.createDate) {
            try {
                createDate = new Date(safeData.createDate.replace("月", "-").replace(",", "")).toLocaleDateString();
            } catch (error) {
                console.error('日期格式错误:', error);
                createDate = '日期格式错误';
            }
        }

        // 直接在 showGoodsData 中计算利润
        let profit = 'N/A';
        if (safeData.price!== 'N/A' && safeData.inPrice!=='N/A') {
            profit = safeData.price - safeData.inPrice;
        }


        // 创建元素并添加内容
        const container = document.createElement('div');
        const idPara = document.createElement('p');
        idPara.textContent = '商品ID: ' + safeData.id;
        const categoryPara = document.createElement('p');
        categoryPara.textContent = '商品类别: ' + safeData.categoryId;
        const namePara = document.createElement('p');
        namePara.textContent = '商品名称: ' + safeData.name;
        const pricePara = document.createElement('p');
        pricePara.textContent = '商品价格: ' + safeData.price;
        const descriptionPara = document.createElement('p');
        descriptionPara.textContent = '商品描述: ' + safeData.description;
        const inPricePara = document.createElement('p');
        inPricePara.textContent = '商品进价: ' + safeData.inPrice;
        const numberPara = document.createElement('p');
        numberPara.textContent = '商品数量: ' + safeData.number;
        const createDatePara = document.createElement('p');
        createDatePara.textContent = '生产日期: ' + createDate;
        const shelfLifePara = document.createElement('p');
        shelfLifePara.textContent = '保质期: ' + safeData.shelfLife;
        const supplierIdPara = document.createElement('p');
        supplierIdPara.textContent = '供应商ID: ' + safeData.supplier_id;
        const profitPara = document.createElement('p');
        profitPara.textContent = '利润（价格 - 进价）: ' + profit;


        // 将元素添加到容器中
        container.appendChild(idPara);
        container.appendChild(categoryPara);
        container.appendChild(namePara);
        container.appendChild(pricePara);
        container.appendChild(descriptionPara);
        container.appendChild(inPricePara);
        container.appendChild(numberPara);
        container.appendChild(createDatePara);
        container.appendChild(shelfLifePara);
        container.appendChild(supplierIdPara);
        container.appendChild(profitPara);


        // 使用 Swal.fire 显示商品详情
        Swal.fire({
            title: '商品详情',
            html: container.innerHTML,
            icon: 'info'
        });
    }

    function calculateRemainingShelfLife(createDate, shelfLife) {
        const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
        const currentDate = new Date();
        const parsedCreateDate = new Date(createDate);
        const diffDays = Math.floor((currentDate - parsedCreateDate) / oneDay);
        return shelfLife - diffDays;
    }

    document.addEventListener('DOMContentLoaded', function () {
        const elements = document.querySelectorAll('.remaining-shelf-life');
        elements.forEach(element => {
            const createDate = element.getAttribute('data-create-date');
            const shelfLife = parseInt(element.getAttribute('data-shelf-life'));
            const remainingShelfLife = calculateRemainingShelfLife(createDate, shelfLife);
            if (remainingShelfLife < 0) {
                element.textContent = '已过期';
            } else {
                element.textContent = remainingShelfLife;
            }
        });
    });
</script>
<div class="main-container">
    <h1>商品查询</h1>
    <form action="/goodsSelect" method="get" class="filter-form" onsubmit="return validateForm()">
        <div class="col-md-2">
            <div class="form-group">
                <label for="categoryId">商品类别：</label>
                <select id="categoryId" name="categoryId">
                    <option value="">全部</option>
                    <c:forEach items="${categoryList}" var="category">
                        <option value="${category.id}">${category.name}</option>
                    </c:forEach>
                </select>
            </div>
        </div>
        <div class="col-md-2">
            <div class="form-group">
                <label for="numberOrder">商品数量：</label>
                <select id="numberOrder" name="numberOrder">
                    <option value="">不排序</option>
                    <option value="asc">升序</option>
                    <option value="desc">降序</option>
                </select>
            </div>
        </div>
        <div class="col-md-2">
            <div class="form-group">
                <label for="shelfLifeOrder">剩余保质期：</label>
                <select id="shelfLifeOrder" name="shelfLifeOrder">
                    <option value="">不排序</option>
                    <option value="asc">升序</option>
                    <option value="desc">降序</option>
                </select>
            </div>
        </div>
        <div class="col-md-2">
            <div class="form-group">
                <label for="priceOrder">价格排序：</label>
                <select id="priceOrder" name="priceOrder">
                    <option value="">不排序</option>
                    <option value="asc">升序</option>
                </select>
            </div>
        </div>
        <div class="col-md-2">
            <div class="form-group">
                <label for="supplierId">供应商ID：</label>
                <select id="supplierId" name="supplierId">
                    <option value="">全部</option>
                    <c:forEach items="${supplierList}" var="supplier">
                        <option value="${supplier.id}">${supplier.id} - ${supplier.name}</option>
                    </c:forEach>
                </select>
            </div>
        </div>
        <div class="col-md-2">
            <button type="submit" class="btn btn-primary">查询</button>
            <a href="/goodsSelect" class="btn btn-secondary">重置</a>
        </div>
    </form>
    <div class="table-container">
        <table id="goodsTable">
            <thead>
            <tr>
                <th>商品Id</th>
                <th>商品名称</th>
                <th>商品价格</th>
                <th>商品数量</th>
                <th>剩余保质期</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <c:forEach items="${goodsList}" var="good">
                <tr>
                    <td>${good.getId()}</td>
                    <td>${good.getName()}</td>
                    <td>${good.getPrice()}</td>
                    <td>${good.getNumber()}</td>
                    <td>
                        <span class="remaining-shelf-life" data-create-date="${good.getCreateDate()}"
                              data-shelf-life="${good.getShelfLife()}">计算中...</span>
                    </td>
                    <td>
                        <button class="btn btn-info btn-sm" onclick="showDetails('${good.getId()}')">详情</button>
                    </td>
                </tr>
            </c:forEach>
            </tbody>
        </table>
    </div>


    <!-- 引入 jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <!-- 引入 Bootstrap JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- 引入 SweetAlert2 的 JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.3/dist/sweetalert2.min.js"></script>
</div>